package com.cmcc.aregister.ui.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.cache.CacheManager;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.constant.HelpInc;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.Appointment;
import com.cmcc.aregister.cs.model.MemberModel;
import com.cmcc.aregister.ui.adapter.HaoyuanTipAdapter;

/**
 * 号源提醒
 * @author Administrator
 * 
 */
public class HaoyuanTipActivity extends ParentActivity implements HelpInc {

    private static final String TAG = "HaoyuanTipActivity";
    private ListView appoint_list;
    private List<Appointment> localAppList = new ArrayList<Appointment>();
    private HaoyuanTipAdapter haoyuanTipAdapter;
    private String params;
    private ImageButton btn_add_appoint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(R.layout.p_haoyuan_tip);
    }

    @Override
    protected void setupData() {
        sendGetHaoyuanTipInfoTask();
    }

    @Override
    protected void setupView() {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.haoyuantixing);
        appoint_list = (ListView) findViewById(R.id.appoint_list);
        btn_add_appoint = (ImageButton) findViewById(R.id.btn_add_appoint);
        btn_add_appoint.setOnClickListener(onClickListener);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(HaoyuanTipActivity.this,
                AppointmentActivity.class);
            intent.putExtra("isHaoyuanTip", "yes");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    };

    private HttpAsyncTask sendGetHaoyuanTipInfoTask;

    private void sendGetHaoyuanTipInfoTask() {
        logger.d("----------sendGetHaoyuanTipInfoTask----------");
        JSONObject obj = new JSONObject();
        try {
            obj.put("request_type", Arguments.QueryRemindTaskRemoting);
            obj.put("user_mobile", ConfigUtilHelper.getMobile(app));
            obj.put("channel", "medical_client_android");
            obj.put("version",
                ConfigUtilHelper.getVersionName(getApplication()));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        params = obj.toString();
        String url = Arguments.GET_AUTO_APPOINT_SERVICE_URL;
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "url:" + url);
        }
        sendGetHaoyuanTipInfoTask = new HttpAsyncTask(
            GlobalSetting.XML_HAOYUAN_TIP_LIST, url, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        showProgressDialogNew(R.string.dialog_loading_haoyuan_tip);
        sendGetHaoyuanTipInfoTask
            .setUIHandler(sendGetHaoyuanTipInfoTaskHandler);
        mHttpManager.execute(sendGetHaoyuanTipInfoTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetHaoyuanTipInfoTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetHaoyuanTipInfoTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    localAppList = (List<Appointment>) httpMap
                        .get(Arguments.JSON_HAOYUAN_TIP_LIST);
                    setView();
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    public void setView() {
        if (localAppList != null && localAppList.size() > 0) {
            haoyuanTipAdapter = new HaoyuanTipAdapter(context, localAppList,
                this);
            appoint_list.setAdapter(haoyuanTipAdapter);
            if (ConfigUtilHelper.debug) {
                Log.i(TAG, "localAppList:" + localAppList.size());
            }
        }
    }

    private int position;

    @Override
    public void notifyUI(int msg, int p) {
    }

    @Override
    public void notifyUI(String msg) {
        // TODO Auto-generated method stub

    }

    @Override
    public void notifyUI(int p) {
        position = p;
        // 取消任务
        cancelHaoyuanTipTask(localAppList.get(p).yuyue_id);
        // 删除缓存
        CacheManager.getInstance().deleteHaoyuanTipCacheById(
            localAppList.get(p).yuyue_id);
    }

    private HttpAsyncTask cancelHaoyuanTipTask;

    private void cancelHaoyuanTipTask(String taskId) {
        logger.d("----------cancelHaoyuanTipTask----------");
        JSONObject obj = new JSONObject();
        try {
            obj.put("request_type", Arguments.CancelRemindTaskRemoting);
            obj.put("user_mobile", ConfigUtilHelper.getMobile(app));
            obj.put("channel", "medical_client_android");
            obj.put("version",
                ConfigUtilHelper.getVersionName(getApplication()));
            obj.put("taskId", taskId);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        params = obj.toString();
        String url = Arguments.GET_AUTO_APPOINT_SERVICE_URL;
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "url:" + url);
        }
        cancelHaoyuanTipTask = new HttpAsyncTask(
            GlobalSetting.XML_CANCEL_HAOYUAN_TIP_TASK, url, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        showProgressDialogNew(R.string.dialog_cancel_haoyuan_tip);
        cancelHaoyuanTipTask.setUIHandler(cancelHaoyuanTipTaskHandler);
        mHttpManager.execute(cancelHaoyuanTipTask);
    }

    Handler cancelHaoyuanTipTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------cancelHaoyuanTipTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String message = (String) httpMap.get(Arguments.RESULT_MSG);
                    String code = (String) httpMap.get(Arguments.RESULT_CODE);
                    if (code.equals("0")) {
                        _showInfoDialog(message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {

                                }
                            });
                    }
                    else {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                }
                else {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.cancel_task_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    public void doSomeWork() {
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "position:" + position);
        }
        app.cancelApp(0, position);
        localAppList.get(position).yuyue_state = "3";
        haoyuanTipAdapter = new HaoyuanTipAdapter(context, localAppList, this);
        appoint_list.setAdapter(haoyuanTipAdapter);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (localAppList != null && localAppList.size() > 0) {
            if (haoyuanTipAdapter == null) {
                haoyuanTipAdapter = new HaoyuanTipAdapter(context,
                    localAppList, this);
                appoint_list.setAdapter(haoyuanTipAdapter);
            }
            else {
                haoyuanTipAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void notifyUI_other(int msg, int position) {
        // TODO Auto-generated method stub

    }

    @Override
    public void notifyUI_other(String id, String arg) {
        // TODO Auto-generated method stub

    }

    @Override
    public void notifyUI_member(MemberModel member) {
        // TODO Auto-generated method stub

    }

}
